<template>
  <div class="app-container">
    <el-splitter :layout="appStore.device === 'mobile'? 'vertical': 'horizontal'" class="default-theme full-hihght">
      <el-splitter-panel size="272" min="172">
        <div class="left-box default-padding">
          <div class="left-head">
            <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search" style="margin-bottom: 16px" />
          </div>
          <div class="left-container" v-loading="deptLoading" element-loading-text="正在加载部门，请稍候">
            <el-tree 
              :data="deptOptions"
              :props="{ label: 'deptName', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="deptId"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick" />
          </div>
        </div>
      </el-splitter-panel>
      <el-splitter-panel>
        <div class="right-box default-padding">
          <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">
            <el-form-item label="" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入账号" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="" prop="nickname">
              <el-input v-model="queryParams.nickname" placeholder="请输入姓名" clearable style="width: 160px" @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="">
              <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-" start-placeholder="最后登录开始日期"
                end-placeholder="最后登录结束日期" style="width: 308px" />
            </el-form-item> -->
            <el-form-item label="" prop="post">
              <el-select v-model="queryParams.post" placeholder="请选择职务" clearable style="width: 160px" @change="handleQuery">
                <el-option v-for="dict in sys_user_post" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item> 
            <el-form-item label="" prop="disable">
              <el-select v-model="queryParams.disable" placeholder="账号状态" clearable style="width: 160px" @change="handleQuery">
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">搜索</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
              <el-button type="success" icon="Upload" @click="handleImport" v-hasPermi="['system:user:import']">导入数据</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['system:user:add']">新增员工</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
          </el-row>

          <el-table border v-loading="loading" :data="userList">
            <el-table-column label="账号" prop="username" v-if="columns[0].visible" />
            <el-table-column label="姓名" prop="nickname" v-if="columns[1].visible" :show-overflow-tooltip="true" />
            <el-table-column label="部门" prop="deptName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
            <el-table-column label="职务" v-if="columns[3].visible" :show-overflow-tooltip="true">
              <template #default="scope">
                <dict-tag :options="sys_user_post" :value="scope.row.extra?.post" />
              </template>
            </el-table-column>
            <el-table-column label="手机号码" prop="phone" v-if="columns[4].visible" width="112" />
            <el-table-column label="账号状态" v-if="columns[5].visible" align="center" width="82">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.disable"
                  :active-value="false"
                  :inactive-value="true"
                  active-text="启用"
                  inactive-text="停用"
                  inline-prompt
                  @change="handleStatusChange(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="最后登录" prop="createTime" v-if="columns[6].visible" width="160">
              <template #default="scope">
                <span>{{ parseTime(scope.row.lastLoginTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="292" class-name="small-padding fixed-width" fixed="right">
              <template #default="scope">
                <el-button link type="primary" icon="View" @click="handleView(scope.row)" v-hasPermi="['system:user:query']">详情</el-button>
                <template v-if="scope.row.userId != '1'"> 
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">编辑</el-button>
                  <el-button link type="primary" icon="Key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']">重置密码</el-button>
                  <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.current" v-model:limit="queryParams.size" @pagination="getList" />
        </div>
      </el-splitter-panel>
    </el-splitter>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" 
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth"
import useAppStore from '@/store/modules/app'
import { listUser, resetUserPwd, delUser, updateUser, addUser } from "@/api/system/user"
import { listDept } from "@/api/system/dept"

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()
const { proxy } = getCurrentInstance()
const { sys_normal_disable, sys_user_post } = proxy.useDict("sys_normal_disable", 'sys_user_post')

const deptLoading = ref(true)
const deptName = ref("")
const deptOptions = ref([])
const uniqueId = ref("")
const loading = ref(true)
const showSearch = ref(true)
const userList = ref([])
const total = ref(0)
const dateRange = ref([])
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
})
// 列显隐信息
const columns = ref([
  { key: 0, label: `账号`, visible: true, disabled: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `部门`, visible: true },
  { key: 3, label: `职务`, visible: true },
  { key: 4, label: `手机号码`, visible: true },
  { key: 5, label: `账号状态`, visible: true },
  { key: 6, label: `最后登录`, visible: true }
])
const queryParams = ref({
  current: 1,
  size: 10,
  nickname: undefined,
  userName: undefined,
  post: undefined,
  disable: undefined,
  deptId: undefined
})

function getDeptTree() {
  deptLoading.value = true
  listDept({ size: -1,  disable: false}).then(response => {
    deptLoading.value = false
    const result = response.result || {}
    let data = proxy.handleTree(result.records, "deptId")
    deptOptions.value = data
  })
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val)
})

function handleNodeClick(data) {
  queryParams.value.deptId = data.deptId
  handleQuery()
}

onActivated(() => {
  const time = route.query.t
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time
    queryParams.value.current = Number(route.query.current)
    getList()
  }
})

/** 查询用户列表 */
function getList() {
  loading.value = true
  listUser(proxy.addDateRange(queryParams.value, dateRange.value)).then(res => {
    const result = res.result || {}
    userList.value = result.records || []
    total.value = Number(result.total)
    loading.value = false
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.current = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = []
  proxy.resetForm("queryRef")
  queryParams.value.deptId = undefined
  proxy.$refs.deptTreeRef.setCurrentKey(null)
  handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
  const userIds = row.userId
  const userNames = row.nickname
  proxy.$modal.confirm('是否确认删除成员姓名为"' + userNames + '"的成员?').then(function () {
    return delUser(userIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = !row.disable ? "启用" : "停用"
  proxy.$modal.confirm('确认要' + text + '"' + row.nickname + '"的用户吗?').then(function () {
    return updateUser({ userId: row.userId, disable: row.disable })
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.disable = row.disable? false : true
  })
}

/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy.$prompt('请输入"' + row.nickname + '"的新密码', "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
    inputValidator: (value) => {
      if (/<|>|"|'|\||\\/.test(value)) {
        return "不能包含非法字符：< > \" ' \\\ |"
      }
    },
  }).then(({ value }) => {
    resetUserPwd(row.userId, value).then(response => {
      proxy.$modal.msgSuccess("修改成功，新密码是：" + value)
    })
  }).catch(() => {})
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入"
  upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/user/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

function handleAdd() {
  const query = { current: queryParams.value.current }
  router.push({ path: "/system/user-data/add", query })
}

function handleUpdate(row) {
  const query = { current: queryParams.value.current }
  router.push({ path: "/system/user-data/edit/" + row.userId, query })
}

function handleView(row) {
  const query = { current: queryParams.value.current }
  router.push({ path: "/system/user-data/view/" + row.userId, query })
}

getDeptTree()
getList()
</script>

<style lang="scss" scoped>
.app-container {
	padding: 0;
	font-size: var(--el-font-size-base);
	.left-box{
    height: 100%;
		display: flex;
		flex-direction: column;
		:deep(.el-input__wrapper) {
			border-radius: 18px;
		}
		.left-head{
			flex-shrink: 1;
		}
		.left-container{
			flex: 1;
			overflow-y: auto;
		}
	}
	.right-box{
    height: 100%;
		overflow-y: auto;
	}
	.default-padding{
		padding: 16px;
	}
}
</style>